package com.centsuse.my_redis.service.impl;

import com.centsuse.my_redis.es.entity.Book;
import com.centsuse.my_redis.es.repositories.BookEsRepository;
import com.centsuse.my_redis.service.IBookEsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.events.Event;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author bobo
 */
@Service
public class BookEsServiceImpl implements IBookEsService {

    @Autowired
    private BookEsRepository bookEsRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;

    @Override
    // 创建索引（如果不存在）
    public void createIndexIfNotExists() {
        if (!elasticsearchOperations.indexOps(Book.class).exists()) {
            elasticsearchOperations.indexOps(Book.class).create();
            // 创建映射
            elasticsearchOperations.indexOps(Book.class).putMapping();
        }
    }

    @Override
    public Book getBook(String isbn) {
        return bookEsRepository.findById(isbn).orElse(null);
    }

    @Override
    public List<Book> getAllBooks() {
        return StreamSupport.stream(bookEsRepository.findAll().spliterator(), false)
                .collect(Collectors.toList());
    }

    @Override
    public Book saveBook(Book book) {
        return bookEsRepository.save(book);
    }

    @Override
    public void deleteBook(String isbn) {
        bookEsRepository.deleteById(isbn);
    }
}
